package producerconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *Description:
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/23 22:07
 */
public class SequentialExecution {

  public static void main(String[] args) {
    Data data=new Data();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        data.printA();
      }
    },"A").start();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        data.printB();
      }
    },"B").start();
    new Thread(()->{
      for (int i = 0; i < 10; i++) {
        data.printC();
      }
    },"C").start();
  }

}
class Data{
  private Lock lock=new ReentrantLock();
  private int flag=1;
  private Condition condition1 = lock.newCondition();
  private Condition condition2 = lock.newCondition();
  private Condition condition3 = lock.newCondition();
  public void printA(){
    lock.lock();
    try {
      while (flag!=1){
        condition1.await();
      }
      System.out.println(Thread.currentThread().getName()+"=>AA");
      flag=2;
      // 唤醒2
      condition2.signal();
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      lock.unlock();
    }
  }
  public void printB(){
    lock.lock();
    try {
      while (flag!=2){
        condition2.await();
      }
      System.out.println(Thread.currentThread().getName()+"=>BB");
      flag=3;
      // 唤醒3
      condition3.signal();
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      lock.unlock();
    }
  }
  public void printC(){
    lock.lock();
    try {
      while (flag!=3){
        condition3.await();
      }
      System.out.println(Thread.currentThread().getName()+"=>CC");
      flag=1;
      // 唤醒1
      condition1.signal();
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      lock.unlock();
    }
  }
}
